package com.btpj.module_main.ui

import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.get
import androidx.navigation.ui.setupWithNavController
import com.btpj.jetpack.base.BaseActivity
import com.btpj.jetpack.base.FixFragmentNavigator
import com.btpj.module_main.R
import com.btpj.module_main.databinding.ActivityMainBinding
import kotlinx.android.synthetic.main.activity_main.*

/**
 * 主页面
 *
 * @author LTP 2020/7/9
 */
class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {

    private lateinit var mNavController: NavController

    override fun getLayoutId() = R.layout.activity_main

    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.AppTheme)
        super.onCreate(savedInstanceState)
        //添加自定义的FixFragmentNavigator
        mNavController = Navigation.findNavController(this, R.id.navHostFragment)
        val fragment =
            supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment
        val fragmentNavigator = FixFragmentNavigator(this, supportFragmentManager, fragment.id)
        mNavController.navigatorProvider.addNavigator(fragmentNavigator)
        mNavController.setGraph(R.navigation.nav_main)
        bottomNavigationView.setupWithNavController(mNavController)
    }

    override fun initView() {

    }

    override fun onBackPressed() {
        // 如果调用 super.onBackPressed()，navigation会操作回退栈,切换到之前显示的页面，导致页面叠加错乱
        //  super.onBackPressed()
        val id = mNavController.currentDestination?.id!!
        val homeNav = mNavController.graph[R.id.nav_home].id
        if (id != homeNav) {
            bottomNavigationView.selectedItemId = R.id.nav_home
        } else {
            finish()
        }
    }
}